package com.servlet;

import com.bean.User;
import com.dao.LoginDaolmp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;


@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public loginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
        response.setContentType("text/html");
        response.setCharacterEncoding("gb2312");
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //请求前端页面的值
        String username = request.getParameter("username"); //获取表单里用户名文本框信息
        String userpwd = request.getParameter("userpwd");//获取表单里用户密码文本框信息
        LoginDaolmp dl = new LoginDaolmp();//实例化对象
        HttpSession session = request.getSession();//
        System.out.println("这是oldsessionID"+session.getId());
        boolean isHave = dl.searchName(username, userpwd);//调用查询用户名和密码是否匹配方法
        if (isHave) {//
            List<User> list = LoginDaolmp.fhui(username, userpwd);
            Iterator<User> iter = list.iterator();
            User u=iter.next();
            session.setAttribute("name",u.getName());
            session.setAttribute("username", username);
            session.setAttribute("userpwd",userpwd);
            request.getRequestDispatcher("/main.jsp").forward(request, response);//带着我们请求取main
        } else {//失败
            request.setAttribute("errormsg", "账号或密码错误请重新登录!");//setattribute  设置位置返回信息
            request.getRequestDispatcher("/index.jsp").forward(request, response);//返回错误信息还是同页面
            //response.sendRedirect("index.jsp");
        }
    }
}